package view.drawable;

import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JComponent;

import model.Circle;
import model.Square;
import view.ControllerEventParser;
import view.IView;
import appmodel.ControllerEvent;
import controller.Controller;

public class DrawableView extends JComponent implements IView {

	private static final long serialVersionUID = 1935258585251278919L;

	final static int MIN_SIZE = 5;

	private List<Circle> circles;
	private List<Square> squares;
	private Controller controller;

	public DrawableView(Controller controllerr) {
		super();
		this.circles = controllerr.getCircles();
		this.squares = controllerr.getSquares();
		this.controller = controllerr;
		controller.registerView(this);
		addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				int size = (int) (((Math.random()*10000)%50) + MIN_SIZE);
				if (e.getButton() == MouseEvent.BUTTON1) {
					controller.addShape(new Square(e.getX(), e.getY(), size));
				}
				if (e.getButton() == MouseEvent.BUTTON3) {
					controller.addShape(new Circle(e.getX(), e.getY(), size));
				}
				DrawableView.this.repaint();
			}
		});
	}

	@Override
	public void onControllerEvent(ControllerEvent event) {
		ControllerEventParser parser = new ControllerEventParser(event){
			@Override
			public void addShape(Circle c) {
				circles = controller.getCircles();
			}
			@Override
			public void addShape(Square s) {
				squares = controller.getSquares();
			}
			@Override
			public void removeShape(Circle c) {
				circles = controller.getCircles();
			}
			@Override
			public void removeShape(Square s) {
				squares = controller.getSquares();
			}
			@Override
			public void refresh() {
				squares = controller.getSquares();
				circles = controller.getCircles();
			}
		};
		parser.processEvent();
		DrawableView.this.repaint();
	}

	@Override
	public void paint(Graphics g) {
		for (Circle c : circles) {
			g.drawOval(c.getX(), c.getY(), c.getR(), c.getR());
		}
		for (Square s : squares) {
			g.drawRect(s.getX(), s.getY(), s.getA(), s.getA());
		}
	}

}
